<template>
  <div class="role-edit-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>编辑角色</h1>
      <div class="action-buttons">
        <el-button @click="handleGoBack">
          <el-icon><ArrowLeft /></el-icon> 返回列表
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon> 保存
        </el-button>
        <el-button @click="resetForm">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
      </div>
    </div>

    <!-- 表单卡片 -->
    <el-card class="form-card">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="formRules"
        label-width="120px"
        class="role-form"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <h2 class="section-title">基本信息</h2>
          <el-divider></el-divider>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" placeholder="请输入角色名称" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="roleForm.code" disabled></el-input>
              <div class="form-hint">角色编码不可修改</div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="角色描述" prop="description">
              <el-input
                v-model="roleForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入角色描述"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="roleForm.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 权限设置提示 -->
        <div class="permission-tip">
          <el-alert
            title="提示"
            type="info"
            description="如需修改角色权限，请通过'权限配置'功能进行操作"
            show-icon
          ></el-alert>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ArrowLeft,
  Check,
  Refresh
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

// 路由实例
const router = useRouter();
const route = useRoute();

// 表单引用
const roleFormRef = ref<any>(null);

// 表单数据
const roleForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: '1'
});

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度2-20位', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '角色描述不能超过500个字符', trigger: 'blur' }
  ]
});

// 返回列表
const handleGoBack = () => {
  router.push({ name: 'RoleList' });
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await roleFormRef.value.validate();

    // 确认提交
    await ElMessageBox.confirm('确定要保存角色信息的修改吗？', '保存确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    // 模拟API请求
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    setTimeout(() => {
      loading.close();
      ElMessage.success('角色信息更新成功');
      router.push({ name: 'RoleDetail', params: { id: roleForm.id } });
    }, 1000);
  } catch (error) {
    // 表单验证失败或用户取消提交
    if (error !== 'cancel') {
      console.error('表单提交失败:', error);
    }
  }
};

// 重置表单
const resetForm = () => {
  getRoleDetail();
};

// 获取角色详情
const getRoleDetail = () => {
  // 显示加载中
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 模拟API请求
  setTimeout(() => {
    const roleId = route.params.id as string;
    const isEnabled = Math.random() > 0.2;

    // 角色类型
    const roleTypes = [
      { name: '超级管理员', code: 'admin', description: '系统最高权限管理员' },
      { name: '财务管理员', code: 'finance', description: '负责财务管理相关功能' },
      { name: '采购管理员', code: 'purchase', description: '负责供应商和采购管理' },
      { name: '销售管理员', code: 'sales', description: '负责销售订单管理' },
      { name: '库存管理员', code: 'inventory', description: '负责库存和物流管理' },
      { name: '普通用户', code: 'user', description: '基础操作权限用户' }
    ];
    const randomRole = roleTypes[Math.floor(Math.random() * roleTypes.length)];

    // 设置表单数据
    Object.assign(roleForm, {
      id: roleId,
      name: randomRole.name,
      code: randomRole.code,
      description: randomRole.description,
      status: isEnabled ? '1' : '0'
    });

    // 关闭加载
    loading.close();
  }, 800);
};

// 页面加载时初始化
onMounted(() => {
  getRoleDetail();
});
</script>

<style scoped lang="scss">
.role-edit-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.role-form {
  padding: 10px 0;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  margin-bottom: 10px;
  color: #303133;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.permission-tip {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .role-edit-container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .action-buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .el-col {
    &.lg-12,
    &.lg-24 {
      flex: 0 0 100%;
      max-width: 100%;
    }
  }
}
</style>